<?php echo $this->element('displayHeader'); ?>
<?php echo $ajax->form('Dispatch', 'post', array('update'=>'content', 'indicator' => 'indicator', 'url' => array('action' => 'save')));?>
<div class="toolbar">
    <div id="tLeft">
        <?php if ($mode == 'add' || $mode == 'revise') : ?>
            <?php echo $this->element('toolbar', array('buttons' => array('save', 'clear', 'back'))); ?>
        <?php elseif (isset($canSave)) :  // mode edit dispatch status == On Dispatch สามารถแก้ Cust see price adjustment ได้ ?>
            <?php echo $this->element('toolbar', array('buttons' => array('save', 'add', 'refresh_view', array('edit' => array('text' => 'Revise', 'params' => $this->data['Dispatch']['id'] . "/revise:true")),
                    array('print' => array('model' => 'Dispatch')), array('print_cust' => array('model' => 'Dispatch')), 'back'))); ?>
        <?php else :  // mode edit ?>
            <?php echo $this->element('toolbar', array('buttons' => array('add', 'refresh_view',
                    array('print' => array('model' => 'Dispatch')),  array('print_cust' => array('model' => 'Dispatch')), 'back'))); ?>
        <?php endif; ?>
    </div>
    <div id="tRight"><?php echo $this->element('neighbors', array('model' => 'Dispatch', 'title' => 'dispatch_no')); ?></div>
</div>

<?php echo $form->input('Dispatch.id'); ?>
<?php echo $form->hidden('mode', array('value' => $mode)); ?>
<?php if ($mode == 'revise') echo $form->hidden('Dispatch.old_id'); ?>
<fieldset>
    <table>
        <tr>
            <td><?php echo $form->label('Dispatch.dispatch_no', 'Dispatch no'); ?></td>
            <td>
                <?php if ($mode == 'add') : ?>
                &nbsp;
                <?php else : ?>
                <span id="dispatch_no"><?php echo $this->data['Dispatch']['dispatch_no'] ?></span>
                    <?php echo $form->hidden('Dispatch.dispatch_no'); ?>
                <?php endif; ?>
            </td>
            <td width="180px"><?php echo $form->label('Dispatch.customer_id', 'Customer', array('class' => 'required')); ?></td>
            <td>
                <?php if ($mode == 'add') : ?>
                    <?php echo $form->hidden('Dispatch.customer_id', array('id' => 'hidDispatchCustomerId')); ?>
                    <?php echo $form->select('Dispatch.customer_id', $customers, null, !empty($this->data['Dispatch']['customer_id'])? array('disabled' => 'disabled', 'tabindex' => 5): array('tabindex' => 5)); ?>
                <?php else : ?>
                    <?php echo $form->hidden('Dispatch.customer_id'); ?>
                <span id="customer_id"><?php echo $this->data['Customer']['name'] ?></span>
                <?php endif; ?>
            </td>
        </tr>
        <tr>
            <td width="180px"><?php echo $form->label('Dispatch.dispatch_date', 'Dispatch date', array('class' => 'required')); ?></td>
            <td width="200px">
                <?php if ($mode == 'add' || $mode == 'revise') : ?>
                    <?php echo $form->text('Dispatch.dispatch_date', array('tabindex' => 1)); ?>
                <?php else : ?>
                <span id="dispatch_date"><?php echo $this->data['Dispatch']['dispatch_date'] ?></span>
                <?php endif; ?>
            </td>
            <td><?php echo $form->label('Dispatch.site_id', 'Site', array('class' => 'required')); ?></td>
            <td>
                <?php if ($mode == 'add') : ?>
                    <?php echo $form->hidden('Dispatch.site_id', array('id' => 'hidDispatchSiteId')); ?>
                    <?php echo $form->select('Dispatch.site_id', isset($sites)? $sites: null, null, !empty($this->data['Dispatch']['site_id'])? array('disabled' => 'disabled', 'tabindex' => 6): array('tabindex' => 6)); ?>
                <?php else : ?>
                    <?php echo $form->hidden('Dispatch.site_id'); ?>
                <span id="site_id"><?php echo $this->data['Site']['name'] ?></span>
                <?php endif; ?>
            </td>
        </tr>
        <tr>
            <td><?php echo $form->label('Dispatch.quotation_no', 'Ref. by Quotation no', array('class' => 'required')); ?></td>
            <td>
                <?php if ($mode == 'add' || $mode == 'revise') : ?>
                    <?php echo $form->text('Dispatch.quotation_no', array('tabindex' => 2)); ?>
                <?php else : ?>
                <span><?php echo $this->data['Dispatch']['quotation_no'] ?></span>
                <?php endif; ?>
            </td>
            <td><?php echo $form->label('Dispatch.warehouse_id', 'From Warehouse', array('class' => 'required')); ?></td>
            <td>
                <?php if ($mode == 'add') : ?>
                    <?php echo $form->hidden('Dispatch.warehouse_id', array('id' => 'hidDispatchWarehouseId')); ?>
                    <?php echo $form->select('Dispatch.warehouse_id', $warehouses); ?>
                <?php else : ?>
                    <?php echo $form->hidden('Dispatch.warehouse_id'); ?>
                <span id="site_id"><?php echo !empty($this->data['Warehouse']['name'])? $this->data['Warehouse']['name']: 'N/A' ?></span>
                <?php endif; ?>
            </td>

        </tr>
        <tr>
            <td><?php echo $form->label('Dispatch.pr_no', 'Ref. by PR no', array('class' => 'required')); ?></td>
            <td>
                <?php if ($mode == 'add' || $mode == 'revise') : ?>
                    <?php echo $form->text('Dispatch.pr_no', array('tabindex' => 3)); ?>
                <?php else : ?>
                <span><?php echo $this->data['Dispatch']['pr_no'] ?></span>
                <?php endif; ?>
            </td>
            <td><?php echo $form->label('Dispatch.to_warehouse', 'To Warehouse', array('class' => 'required')); ?></td>
            <td>
                <?php if ($mode == 'add' || $mode == 'revise') : ?>
                    <?php echo $form->text('Dispatch.to_warehouse', array('tabindex' => 7)); ?>
                <?php else : ?>
                <span><?php echo $this->data['Dispatch']['to_warehouse'] ?></span>
                <?php endif; ?>
            </td>

        </tr>
        <tr>
            <td><?php echo $form->label('Dispatch.csd', 'CSD', array('class' => 'required')); ?></td>
            <td>
                <?php if ($mode == 'add' || $mode == 'revise') : ?>
                    <?php echo $form->text('Dispatch.csd', array('tabindex' => 4)); ?>
                <?php else : ?>
                <span><?php echo $this->data['Dispatch']['csd'] ?></span>
                <?php endif; ?>
            </td>
            <td><?php echo $form->label('Dispatch.deliveree', 'Delivered To', array('class' => 'required')); ?></td>
            <td>
                <?php if ($mode == 'add' || $mode == 'revise') : ?>
                    <?php echo $form->text('Dispatch.deliveree', array('tabindex' => 8)); ?>
                <?php else : ?>
                <span><?php echo $this->data['Dispatch']['deliveree'] ?></span>
                <?php endif; ?>
            </td>
        </tr>
        <tr>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td><label for="DispatchDispatchStatusId">Dispatch Status</label></td>
            <td>
                <?php
                if ($mode == 'edit') {
                    echo $this->data['DispatchStatus']['title'];
                } else {
                    echo $dispatchStatus;
                }
                ?>
            </td>
        </tr>
    </table>
</fieldset>

<fieldset>
    <table class="data">
        <thead>
            <tr>
                <th class="no">No</th>
                <th width="180">Part no.</th>
                <th width="135">Stock code</th>
                <th>Description</th>
                <th width="100px">Deliver Qty</th>
                <th width="50px">Unit</th>
                <th width="80px">Price/Unit</th>
                <th width="75px">Amount</th>
                <?php if($mode != 'revise') : ?>
                <th width="60px">Index</th>
                <?php endif; ?>
                <?php if($mode == 'add' || $mode == 'revise') : ?>
                <th class="action">&nbsp;</th>
                <?php endif; ?>
            </tr>
        </thead>
        <tbody id="productRow">
            <?php if ($mode == 'add') : ?>
            <?php else :
                $count = count($this->data['CustStockIn']);
                $total = 0;
            ?>
                <?php for($i = 0; $i < $count; ++$i) : ?>
            <tr class="<?php echo (($i + 1) % 2 == 0)? 'even-cell' : 'odd-cell'; ?>">
                <td><span><?php echo $i + 1; ?></span></td>
                <td>
                            <?php echo $html->link($this->data['CustStockIn'][$i]['Product']['part_no'],
                            '/products/view/' . $this->data['CustStockIn'][$i]['product_id'] . '/' . strtotime('now'),
                            array('target' => '_blank')); ?>
                    <span id="CustStockIn<?php echo $i; ?>PartNoSpan" style="display: none"><?php echo $this->data['CustStockIn'][$i]['Product']['part_no']; ?></span>
                            <?php echo $form->hidden("CustStockIn.{$i}.product_id"); ?>
                            <?php echo $form->hidden("CustStockIn.{$i}.cust_product_site_id"); ?>
                </td>
                <td><?php echo $this->data['CustStockIn'][$i]['CustProductSite']['stock_code']; ?></td>
                <td>
                            <?php echo !empty($this->data['CustStockIn'][$i]['CustProductSite']['text'])?
                            $this->data['CustStockIn'][$i]['CustProductSite']['text']:
                            $this->data['CustStockIn'][$i]['Product']['text']; ?>
                </td>
                        <?php if ($mode == 'revise') : ?>
                <td>
                                <?php echo $form->input("CustStockIn.{$i}.deliver_qty", array('label' => false, 'div' => array('class' => 'inline'), 'size' => 3, 'maxlength' => 3, 'class' => 'text-right', 'no' => $i));?>
                    <span id="CustStockIn<?php echo $i; ?>MaxQty">/<?php echo $this->data['CustStockIn'][$i]['Product']['current_stock'] + $this->data['CustStockIn'][$i]['deliver_qty']; ?></span>
                </td>
                        <?php else : ?>
                <td class="text-right">
                                <?php echo $this->data['CustStockIn'][$i]['deliver_qty']; ?>
                </td>
                        <?php endif; ?>
                <td class="center">
                            <?php echo $this->data['CustStockIn'][$i]['Product']['Unit']['title']; ?>
                </td>
                <td class="text-right">
                            <?php if ($mode == 'revise') : ?>
                                <?php echo $form->text("CustStockIn.{$i}.quotation_price", array('size' => 10, 'maxlength' => 10, 'class' => 'text-right', 'no' => $i));?>
                            <?php else : ?>
                                <?php echo number_format($this->data['CustStockIn'][$i]['quotation_price'], 2); ?>
                            <?php endif; ?>
                </td>
                <td class="text-right">
                    <span id="CustStockIn<?php echo $i; ?>TotalQuotationPrice">
                <?php
                $amount = $this->data['CustStockIn'][$i]['quotation_price'] * $this->data['CustStockIn'][$i]['deliver_qty'];
                $total += $amount;
                echo number_format($amount, 2);
                ?>
                    </span>
                </td>
                        <?php if ($mode != 'revise') : ?>
                <td class="center">
                                <?php echo $ajax->link($html->image('icon/popup.png', array('alt' => 'Index information')),
                                array('controller' => 'products_serials', 'action' => 'popup_view', $this->data['CustStockIn'][$i]['product_id'] . '/its_stock_out_id:' . $this->data['CustStockIn'][$i]['id'] . '/its_stock_out_type:' . CustStockIn::ITS_STOCK_OUT_TYPE),
                                array('update' => 'content', 'position' => 'bottom', 'indicator' => 'indicator' ), null, false); ?>
                </td>
                        <?php else : ?>
                <td class="center"><a href="#" id="linkCustStockIn<?php echo $i; ?>Delete" style="display: none;"><?php echo $html->image('icon/delete.png', array('title' => 'Delete', 'alt' => 'Delete')); ?></a></td>
                        <?php endif; ?>
            </tr>
                <?php endfor; ?>
            <?php endif; ?>
        </tbody>
        <tfoot>
            <tr>
                <td colspan="7" class="text-right">Total</td>
                <td class="text-right">
                    <span id="spanTotal">
                        <?php if ($mode != 'add') echo number_format($total, 2); ?>
                    </span>
                </td>
                <td <?php if ($mode == 'add') echo 'colspan="2"'; ?>>&nbsp;</td>
            </tr>
        </tfoot>
    </table>
</fieldset>

<fieldset>
    <div>
        <label>Cutomer can see price adjustment :</label>
        <span id="see_price_adjustment">
            <?php echo $form->checkbox('Dispatch.cust_see_price_adjustment'); ?> Yes/No

        </span>
    </div>
    <div>
        <label>Price Adjustment Case :</label>
        <span id="PriceAdjustmentCase"><?php echo !empty($this->data['Dispatch']['price_adjustment_case'])? $this->data['Dispatch']['price_adjustment_case'] : ''; ?></span>
        <?php if ($mode == 'add' || $mode == 'revise') echo $form->hidden('Dispatch.price_adjustment_case', array('id' => 'PriceAdjustmentCaseHidden')); ?>
    </div>
    <table class="data" style="width: auto;">
        <tr>
            <th>Price Adjustment 1</th><th width="150px">Date</th>
            <th>Price Adjustment 2</th><th width="150px">Date</th>
        </tr>
        <tr class="odd-cell">
            <td>Valid for quote price to</td>
            <td class="center">
                <span id="QuotePriceValidTo"><?php echo !empty($this->data['Dispatch']['quote_price_valid_to'])? $this->data['Dispatch']['quote_price_valid_to'] : ''; ?></span>
                <?php echo $form->hidden('Dispatch.quote_price_valid_to', array('id' => 'QuotePriceValidToHidden')); ?>
            </td>
            <td>2nd Price Adjustment on</td>
            <td class="center">
                <span id="PriceAdjustment2Date"><?php echo !empty($this->data['Dispatch']['price_adjustment_2_date'])? $this->data['Dispatch']['price_adjustment_2_date'] : ''; ?></span>
                <?php echo $form->hidden('Dispatch.price_adjustment_2_date', array('id' => 'PriceAdjustment2DateHidden')); ?>
            </td>
        </tr>
        <tr class="even-cell">
            <td>1st Price Adjustment on</td>
            <td class="center">
                <span id="PriceAdjustment1Date"><?php echo !empty($this->data['Dispatch']['price_adjustment_1_date'])? $this->data['Dispatch']['price_adjustment_1_date'] : ''; ?></span>
                <?php echo $form->hidden('Dispatch.price_adjustment_1_date', array('id' => 'PriceAdjustment1DateHidden')); ?>
            </td>
            <td>Valid for 2nd Adjunstment to</td>
            <td class="center">
                <span id="PriceAdjustment2ValidTo"><?php echo !empty($this->data['Dispatch']['price_adjustment_2_valid_to'])? $this->data['Dispatch']['price_adjustment_2_valid_to'] : ''; ?></span>
                <?php echo $form->hidden('Dispatch.price_adjustment_2_valid_to', array('id' => 'PriceAdjustment2ValidToHidden')); ?>
            </td>
        </tr>
        <tr class="odd-cell">
            <td>Valid for 1st Adjustment to</td>
            <td class="center">
                <span id="PriceAdjustment1ValidTo"><?php echo !empty($this->data['Dispatch']['price_adjustment_1_valid_to'])? $this->data['Dispatch']['price_adjustment_1_valid_to'] : ''; ?></span>
                <?php echo $form->hidden('Dispatch.price_adjustment_1_valid_to', array('id' => 'PriceAdjustment1ValidToHidden')); ?>
            </td>
            <td>Customer must purchase on</td>
            <td class="center">
                <span id="CustPurchaseDate"><?php echo !empty($this->data['Dispatch']['cust_purchase_date'])? $this->data['Dispatch']['cust_purchase_date'] : ''; ?></span>
                <?php echo $form->hidden('Dispatch.cust_purchase_date', array('id' => 'CustPurchaseDateHidden')); ?>
            </td>
        </tr>
    </table>
</fieldset>

<?php echo $form->end(); ?>
<?php echo $form->hidden('supplier_id'); ?>

<?php if ($mode == 'add'|| $mode == 'revise') : ?>
<script type="text/javascript">

    var mode = $j('#mode').val();

    // function คำนวณ price adjustment case
    calPriceCase = function() {
        var dispatchDateStr = $j('#DispatchDispatchDate').val();

        if (dispatchDateStr.length == 0) {
            return;
        }

        var dateArray = dispatchDateStr.split("/");
        var dispatchDay = dateArray[0];
        var dispatchMonth = dateArray[1];
        var dispatchYear = dateArray[2];

        // ตรวจสอบ Price adjustment case
        // ครึ่งปีแรก กรณี 1 ครึ่งปีหลัง กรณี 2
        if (dispatchMonth < 7) {
            $('PriceAdjustmentCase').update(1);
            $('PriceAdjustmentCaseHidden').value = 1;

            var QuotePriceValidTo = '31/12/' + dispatchYear;
            $('QuotePriceValidTo').update(QuotePriceValidTo);
            $('QuotePriceValidToHidden').value = QuotePriceValidTo;

            var PriceAdjustment1Date = '01/01/' + (new Number(dispatchYear) + 1);
            $('PriceAdjustment1Date').update(PriceAdjustment1Date);
            $('PriceAdjustment1DateHidden').value = PriceAdjustment1Date;

            var PriceAdjustment1ValidTo = '31/12/' + (new Number(dispatchYear) + 1);
            $('PriceAdjustment1ValidTo').update(PriceAdjustment1ValidTo);
            $('PriceAdjustment1ValidToHidden').value = PriceAdjustment1ValidTo;

            var PriceAdjustment2Date = '01/01/' + (new Number(dispatchYear) + 2);
            $('PriceAdjustment2Date').update(PriceAdjustment2Date);
            $('PriceAdjustment2DateHidden').value = PriceAdjustment2Date;

            var PriceAdjustment2ValidTo = '31/12/' + (new Number(dispatchYear) + 2);
            $('PriceAdjustment2ValidTo').update(PriceAdjustment2ValidTo);
            $('PriceAdjustment2ValidToHidden').value = PriceAdjustment2ValidTo;

            var CustPurchaseDate = '01/01/' + (new Number(dispatchYear) + 3);
            $('CustPurchaseDate').update(CustPurchaseDate);
            $('CustPurchaseDateHidden').value = CustPurchaseDate;

        } else {
            $('PriceAdjustmentCase').update(2);
            $('PriceAdjustmentCaseHidden').value = 2;

            var QuotePriceValidTo = '31/12/' + (new Number(dispatchYear) + 1);
            $('QuotePriceValidTo').update(QuotePriceValidTo);
            $('QuotePriceValidToHidden').value = QuotePriceValidTo;

            var PriceAdjustment1Date = '01/01/' + (new Number(dispatchYear) + 2);
            $('PriceAdjustment1Date').update(PriceAdjustment1Date);
            $('PriceAdjustment1DateHidden').value = PriceAdjustment1Date;

            var PriceAdjustment1ValidTo = '31/12/' + (new Number(dispatchYear) + 2);
            $('PriceAdjustment1ValidTo').update(PriceAdjustment1ValidTo);
            $('PriceAdjustment1ValidToHidden').value = PriceAdjustment1ValidTo;

            // case 2 ไม่มีการปรับราคาครั้งที่ 2
            $('PriceAdjustment2Date').update('-');
            $('PriceAdjustment2DateHidden').value = '';

            $('PriceAdjustment2ValidTo').update('-');
            $('PriceAdjustment2ValidToHidden').value = '';

            var CustPurchaseDate = '01/01/' + (new Number(dispatchYear) + 3);
            $('CustPurchaseDate').update(CustPurchaseDate);
            $('CustPurchaseDateHidden').value = CustPurchaseDate;

        }
    };

    $j(function() {
        $j('#DispatchDispatchDate').datepicker(Object.extend(Object.clone(datepicker_options),{
            onClose: calPriceCase
        }));

        calPriceCase();
    });

    // JSON เก็บ part no ที่ป้อนเข้ามา อ้างไปยังลำดับแถว
    var partNos = {};

    requestProduct = function(event, notRequestCPS) {
        var element = Event.element(event);
        var part_no = $j.trim($F(element)).toUpperCase();
        var no = element.readAttribute("no");   // ลำดับแถวปัจจุบัน เริ่มที่ 0
        if(part_no.length == 0) {
            //alert("No part no");
            return;
        }

        if (mode == 'add') {
            if ($j("#DispatchSiteId").val() == "") {
                alert("Please select a customer site.");
                $(event.target).clear();
                return;
            } else if ($F("DispatchWarehouseId") == "") {
                alert("Please select a warehouse.");
                $(event.target).clear();
                return;
            } else {
                $("DispatchCustomerId").disable();
                $("DispatchSiteId").disable();
                $("DispatchWarehouseId").disable();
                $("hidDispatchCustomerId").value = $F("DispatchCustomerId");
                $("hidDispatchSiteId").value = $F("DispatchSiteId");
                $("hidDispatchWarehouseId").value = $F("DispatchWarehouseId");
            }
        }

        // ถ้ายังไม่มี part no นี้อยู่
        if (partNos[part_no] == null) {
            var url = base + "/dispatches/json_find_by_part_no_site_id/";
            var params = {part_no: part_no, site_id: $j("#DispatchSiteId").val(), warehouse_id: $j("#DispatchWarehouseId").val()};
            postRequest(url, params, function(data) {
                if (data.CustProductSite) { // มีทั้ง CustProductSite และ product
                    if (data.CustProductSite.dispatch_from != null && (data.CustProductSite.dispatch_from != ITS_PREFIX && data.CustProductSite.current_stock != 0)) {
                        alert("You couldn't dispatch this product at this time.");
                        element.clear();
                        $("CustStockIn" + no + "PartNo").focus();
                    } else {
                        if (data.Product.current_stock == 0) { // ไม่มี product อยู่ใน stock
                            alert("This product is out of stock.<br />(current stock = 0)");
                            $("CustStockIn" + no + "StockCode").update();
                            $("CustStockIn" + no + "QuotationPrice").update();
                            element.clear();
                            return;
                        }

                        $j("#CustStockIn" + no + "CustProductSiteId").val(data.CustProductSite.id);
                        $("CustStockIn" + no + "StockCode").update(data.CustProductSite.stock_code);
                        $("CustStockIn" + no + "ProductStockCode").value = data.CustProductSite.stock_code;
                        $("CustStockIn" + no + "QuotationPrice").value = data.CustProductSite.price != null? data.CustProductSite.price: 0;

                        // ถ้า CPS นี้ยกเลิกการใช้งานแล้วจะ dispatch ไปให้ไม่ได้
                        if (data.CustProductSite.discontinued == true) {
                            alert("This product has been discontinued for this customer.");
                            $("CustStockIn" + no + "StockCode").update();
                            $("CustStockIn" + no + "QuotationPrice").update();
                            element.clear();
                            return;
                        }

                        setCustStockIn(data, part_no, no);
                    }
                } else if (data.Product) { // มี product อย่างเดียว (ยังไม่ได้ add stock code)
                    if (notRequestCPS == null) {
                        requestPopupCustProductSite(data.Product.id, event);
                    }
                } else { // ไม่พบข้อมูล (กรอกข้อมูลผิด...)
                    alert("No product found.");
                    element.clear();
                    $("CustStockIn" + no + "PartNo").focus();
                }
            }
        );
        } else {
            element.clear();
            var row = partNos[part_no]; // แถวที่มี part_no นี้อยู่
            $j("#CustStockIn" + row + "DeliverQty").val(parseInt($j("#CustStockIn" + row + "DeliverQty").val()) + 1);
            calAmount(row);
            setTimeout(function() {
                $("CustStockIn" + no + "PartNo").focus();
            }, 100);
        }
    }

    setCustStockIn = function(data, part_no, no) {
        $("CustStockIn" + no + "Text").update(data.CustProductSite.text != null? data.CustProductSite.text: data.Product.text);
        $("CustStockIn" + no + "PartNo").hide();
       $j("#linkCustStockIn" + no + "ProductId").hide();
        $("CustStockIn" + no + "PartNoSpan").update(data.Product.part_no);
        $("CustStockIn" + no + "PartNoSpan").show();
        $("CustStockIn" + no + "ProductId").value = data.Product.id;
        $("CustStockIn" + no + "MaxQty").update("/" + data.Product.current_stock);
        $("CustStockIn" + no + "ProductUnit").update(data.Product.Unit.title);
        $("CustStockIn" + no + "DeliverQty").value = 1;
        $j('#supplier_id').val(data.Product.supplier_id)

        // กดปุ่มดู Index
        $j("#CustStockIn" + no + "Index").bind('click', function(event) {
            requestPopup(base + '/products_serials/popup_view/' + data.Product.id + '/warehouse_id:' + $j('#DispatchWarehouseId').val());
        });

        // ดักจับ Event กดลบแถว
        linkDelete(no);

        partNos[part_no] = no;  // บันทึกแถวปัจจุบันของ part no
        calAmount(no);
        var nextRow = (parseInt(no) + 1);
        createRow(nextRow);
        $("CustStockIn" + nextRow + "PartNo").focus();
    }

    requestPopupCustProductSite = function(product_id, product_event) {
        var url = base + '/its_cust_product_sites/popup_view';
        url += "/customer_id:" + $j("#DispatchCustomerId").val();
        url += "/site_id:" + $j("#DispatchSiteId").val();
        url += "/product_id:" + product_id;
        requestPopup(url, null, function() {
            $j('#popup').bind('dialogbeforeclose', function(event, ui) {
                requestProduct(product_event, false);
            });
        });
    }

    linkDelete = function(no) {
        $j('#linkCustStockIn' + no + 'Delete').bind('click', function() {
            // ลบรายการ part no ออกจาก list
            var p = $j("#CustStockIn" + no + "PartNoSpan").text();
            partNos[p] = undefined;

            // ลบ แถว
            $j('#CustStockIn' + no + 'PartNoSpan').parents('tr').remove();

            // จัดลำดับตัวเลขหน้าแถวใหม่
            $j('#productRow').runno();
        }).show();
    }

    calAmount = function(no) {
        var deliverQty = parseInt($F("CustStockIn" + no + "DeliverQty"));
        var maxQty = parseInt($("CustStockIn" + no + "MaxQty").innerHTML.substring(1));
        if (deliverQty > maxQty) {
            alert("Please stock out quantity less than current stock quantity.");
            $("CustStockIn" + no + "DeliverQty").value = maxQty;
            return;
        }
        var price = parseFloat($F("CustStockIn" + no + "QuotationPrice"));
        var amount = deliverQty * price;
        $("CustStockIn" + no + "TotalQuotationPrice").update(amount.toFixed(2));

        var total = 0;
        // calculate total
        $j('span[id$=TotalQuotationPrice]').each(function() {
            var amount = parseFloat($j.trim($j(this).html()).replace(',', ''));
            if (!isNaN(amount)) {
                total += amount;
            }
        });
        $j('#spanTotal').html(total.toFixed(2));
    }

    createRow = function(row) {
        var tBody = $("productRow");
        var tr = new Element("tr");
        tr.addClassName((row + 1) % 2 == 0? "even-cell" : "odd-cell");

        tr.update('<input id="CustStockIn' + row + 'Id" type="hidden" value="" name="data[CustStockIn][' + row + '][id]" />');

        var tdNo = new Element("td");
        tdNo.update('&nbsp;');
        tr.insert(tdNo);

        var tdPartNo = new Element("td");
        tdPartNo.insert('<input id="CustStockIn' + row + 'PartNo" type="text" value="" no="' + row + '" name="data[CustStockIn][' + row + '][part_no]"/>');
        tdPartNo.insert('<input id="CustStockIn' + row + 'ProductId" type="hidden" value="" name="data[CustStockIn][' + row + '][product_id]"/>');
        tdPartNo.insert('<input id="CustStockIn' + row + 'CustProductSiteId" type="hidden" value="" name="data[CustStockIn][' + row + '][cust_product_site_id]"/>');
        tdPartNo.insert('<span id="CustStockIn' + row + 'PartNoSpan" style="display: none"></span>');
        tdPartNo.insert('&nbsp;<a href="#" id="linkCustStockIn' + row + 'ProductId"><?php echo $html->image('icon/search.png'); ?></a>');
        tr.insert(tdPartNo);

        var tdStockCode = new Element("td");
        tdStockCode.insert('<span id="CustStockIn' + row + 'StockCode"></span>');
        tdStockCode.insert('<input id="CustStockIn' + row + 'ProductStockCode" type="hidden" value="" name="data[CustStockIn][' + row + '][product_stock_code]"/>');
        tr.insert(tdStockCode);

        var tdTitle = new Element("td");
        tdTitle.insert('<span id="CustStockIn' + row + 'Text"></span>');
        tr.insert(tdTitle);

        var tdDeliverQty = new Element("td");
        var div = new Element("div", {'class': 'inline'});
        div.update('<input id="CustStockIn' + row + 'DeliverQty" no="' + row + '" class="text-right" type="text" value="" maxlength="3" size="3" name="data[CustStockIn][' + row + '][deliver_qty]"/>');
        div.insert('<span id="CustStockIn' + row + 'MaxQty"></span>');
        tdDeliverQty.insert(div);
        tr.insert(tdDeliverQty);

        var tdUnit = new Element("td", {'class': 'center'});
        tdUnit.insert('<span id="CustStockIn' + row + 'ProductUnit"></span>');
        tr.insert(tdUnit);

        var tdPrice = new Element("td");
        tdPrice.insert('<input id="CustStockIn' + row + 'QuotationPrice" no="' + row + '" class="text-right" type="text" value="" maxlength="10" size="10" name="data[CustStockIn][' + row + '][quotation_price]" />');
        tr.insert(tdPrice);

        var tdAmount = new Element("td", {'class': 'text-right'});
        tdAmount.insert('<span id="CustStockIn' + row + 'TotalQuotationPrice"></span>');
        tr.insert(tdAmount);

        if (mode == 'add') {
            var tdIndex = new Element("td", {id: 'tdIndex' + row, "class": "center"});
            tdIndex.insert('<a href="#" id="CustStockIn' + row + 'Index"><?php echo $html->image('icon/popup.png', array('title' => 'Index', 'alt' => 'Index')); ?>');
            tr.insert(tdIndex);
        }

        var tdDelete = new Element("td", {"class": "center"});
        tdDelete.insert('<a href="#" id="linkCustStockIn' + row + 'Delete" style="display: none;"><?php echo $html->image('icon/delete.png', array('title' => 'Delete', 'alt' => 'Delete')); ?></a>');
        tr.insert(tdDelete);

        tBody.insert(tr);

        $j('#productRow').runno();
        addRowListener(row);
    }

   productsHandler = function(part_no) {
        if (part_no != null) {
            // หา input part no ที่ยังแสดงอยู่ (มีอันเดียวเสมอ)
            $j("input[id$=PartNo]:visible").val(part_no).focus().blur();
        }
    }

    addRowListener = function(row, revise) {
        if (revise != true) {
            $("CustStockIn" + row + "PartNo").observe('keypress', partNoKeyPress);
            $("CustStockIn" + row + "PartNo").observe('blur', function(event) {
                requestProduct(event);
            });
        }

        $j("#linkCustStockIn" + row + "ProductId").bind('click', function(event) {

            if (mode == 'add') {
                if ($j("#DispatchSiteId").val() == "") {
                    alert("Please select a customer site.");
                    return;
                } else if ($F("DispatchWarehouseId") == "") {
                    alert("Please select a warehouse.");
                    return;
                }
            }
            var url = base + "/products/popup_view";
            // ถ้าเลือก Vendor แล้วส่งไปเป็นเงื่อนไขด้วยเลย
            if ($j('#CustStockInHeadSiteId').val() != "") {
                url += "/site_id:" + $j('#DispatchSiteId').val();
            }

            if ($j('#supplier_id').val() != "") {
                url += "/supplier_id:" + $j('#supplier_id').val();
            }
            requestPopup(url, "productsHandler");
        });


        $("CustStockIn" + row + "DeliverQty").observe('keypress', stopKeyEnter);
        $("CustStockIn" + row + "DeliverQty").observe('change', function(event) {
            calAmount(Event.element(event).readAttribute("no"));
        });

        $("CustStockIn" + row + "QuotationPrice").observe('keypress', stopKeyEnter);
        $("CustStockIn" + row + "QuotationPrice").observe('change', function(event) {
            calAmount(Event.element(event).readAttribute("no"));
        });
    }

    $j(function() {
        /**
         * validate ข้อมูลด้วย javascript ก่อน
         */
        $j('#DispatchId').parent('form').beforeSubmit(function() {
            if ($j.areEmpty('DispatchDispatchDate', 'DispatchQuotationNo', 'DispatchPrNo', 'DispatchCsd', 'DispatchCustomerId', 'DispatchSiteId', 'DispatchWarehouseId', 'DispatchToWarehouse', 'DispatchDeliveree')) {
                return false;
            }

            if (!$j.validateColumns('ProductId', 'Product', {callback: $j.EMPTY})) {
                return false;
            }

            if (!$j.validateColumns('QuotationPrice', 'Price/Unit', {callback: $j.AMOUNT})) {
                return false;
            }

            if (!$j.validateColumns('DeliverQty', 'Deliver Qty', {callback: $j.QTY})) {
                return false;
            }

            return true;
        });

        if (mode == 'revise') {

            var tr = $j('#productRow').children();
            tr.each(function(i) {
                partNos[$j('#CustStockIn' + i + 'PartNoSpan').text()] = i;  // บันทึกแถวปัจจุบันของ part no
                addRowListener(i, true);
                linkDelete(i);
            });
        } else {
            $j("#DispatchCustomerId").bind('change', function() {
                requestOptions("sites", "DispatchCustomerId", "DispatchSiteId");
                requestJSON('customers', $F(this), function(data) {
                    if (data.Customer.see_price_adjustment == true) {
                        $j("#DispatchCustSeePriceAdjustment").attr('checked', true);
                    } else {
                        $j("#DispatchCustSeePriceAdjustment").removeAttr('checked');
                    }
                });
            });
        }
        createRow($j('#productRow').children().length);
    })

</script>
<?php endif; ?>

<?php //debug($this->data); ?>